<?php
/**
 * quick_curd
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站地址: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: 2024/12/15
 * 描述:
 */

namespace app\result;

use app\model\AccessLog;
use app\model\user\User;

class AccessLogResult extends BaseResult
{
    public function __construct()
    {
        parent::__construct();
        $this->model = new AccessLog();
    }

    // 记录访问日志
    public static function add($header)
    {
        $versioncode = $header['versioncode'] ?? 0;//112
        $version = strtolower($header['version'] ?? '');//1.0.12
        $platform = strtolower($header['platform'] ?? '');//ios android
        $bs_from = strtolower($header['bsfrom'] ?? '');//h5/xcx/app

        $user_agent = $header['user-agent'] ?? '';
        //bs_log($header, 'header', 'header.log');
        if (empty($bs_from)) {
            if (preg_match('/MicroMessenger/i', $user_agent)) {
                $bs_from = 'xcx';
            } elseif (empty($header['referer'])) {
                $bs_from = 'app';
            } else {
                $bs_from = 'app';
            }
        }

        $agentInfo = self::getOSAndVersion($user_agent);
        $token = $header['authorization'] ?? '';
        if ($token) {
            $token = trim(str_replace('Bearer', '', $token));
            $userCheck = (new UserResult())->get_token_user($token, 'user_id');
            $user = $userCheck['code'] === 0 ? $userCheck['data'] : [];
        }
        $url = $header['url'] ?? '';
        if (stripos($url, '/admin/') !== false) {
            return true;
        }

        $ip = !empty($header['ip']) ? $header['ip'] : get_ip();
        $ip2address = ToolsResult::ip2region($ip);
        $args = [
            'appid' => $header['appid'] ?? '',
            'ip' => $ip ?? '',
            'user_agent' => $user_agent ?? '',
            'referer' => $header['referer'] ?? '',
            'platform' => $platform,
            'bs_from' => $bs_from,
            'method' => $header['method'] ?? '',
            'url' => $url,
            'user_id' => $user['user_id'] ?? 0,
            'os_version' => $agentInfo['version'] ?? '',
            'os' => $agentInfo['os'] ?? (!empty($header['referer'] ? 'web' : '')),
            'app_version' => $version,
            'country' => $ip2address['country'] ?? '',
            'province' => $ip2address['province'] ?? '',
            'city' => $ip2address['city'] ?? '',
        ];
        config(['debug' => false], 'database');//关闭数据库SQL日志
        $model = new AccessLog();
        $model->data_add($args);
        if (!empty($user['user_id'])) {
            $upData = [
                'last_active_time' => $header['time'] ?? time(),
            ];
            if ($args['app_version']) {
                $upData['last_active_version'] = $args['app_version'];
            }
            if ($args['bs_from']) {
                $upData['last_active_platform'] = $args['bs_from'] ?? '';
            }

            (new UserResult())->update_last_active_time($user['user_id'], $upData);
        }
        return self::success_return();
    }


    private static function getOSAndVersion($userAgent)
    {
        $os = '';
        $os_version = 0;
        if (stripos(strtolower($userAgent), 'mac os x') !== false) {
            $os = 'ios';
            if (preg_match('/Version\/(\d+)\.(\d+)/', $userAgent, $version)) {
                $os_version = $version[1] . '.' . $version[2];
            }
        } elseif (strpos($userAgent, 'Android') !== false) {
            $os = 'android';
            if (preg_match('/Android (\d+(\.\d+)?)/', $userAgent, $matches)) {
                $os_version = $matches[1];
            }
        } elseif (strpos($userAgent, 'Windows') !== false) {
            $os = 'windows';
            if (preg_match('/NT (\d+(\.\d+)?)/', $userAgent, $matches)) {
                $os_version = $matches[1];
            }
        } elseif (stripos(strtolower($userAgent), 'linux') !== false) {
            $os = 'linux';
        } elseif (stripos(strtolower($userAgent), 'mac') !== false) {
            $os = 'mac';
        } elseif (stripos(strtolower($userAgent), 'iphone') !== false) {
            $os = 'ios';
            if (preg_match('/OS (\d+)_(\d+)_(\d+)/', $userAgent, $version)) {
                $os_version = $version[1] . '.' . $version[2] . '.' . $version[3];
            }
        }


        return ['os' => $os, 'os_version' => $os_version];
    }

    public function list($args = [])
    {
        $page = intval($args['page'] ?? 1);
        $pageSize = intval($args['limit'] ?? 10);
        $user_id = intval($args['user_id'] ?? 0);
        $created_at = $args['created_at'] ?? [];
        $where = [];
        if (!empty($args['keyword'])) {
            $where[] = ['app_version|bs_from|platform|os|city|province|ip|url|method', 'like', '%' . trim($args['keyword']) . '%'];
        }
        if ($user_id) {
            $where[] = ['user_id', '=', $user_id];
        }
        if ($created_at) {
            $where[] = ['created_at', 'between', [$created_at[0], $created_at[1]]];
        }
        $total = $this->model->data_count($where);
        $data = $this->model->data_list($where, 'id,ip,user_id,bs_from,url,method,app_version,platform,os,created_at,province,city', 'id desc', $page, $pageSize);
        if ($data) {
            $allUser = (new User())->data_list_nopage([['user_id', 'in', array_column($data->toArray(), 'user_id')]], 'user_id,account');
            if ($allUser) {
                $userMap = array_column($allUser, 'account', 'user_id');
            }
            foreach ($data as &$item) {
                $item['address'] = $item['province'] . '/' . $item['city'];
                $item['user_account'] = $userMap[$item['user_id']] ?? $item['user_id'];
            }
            unset($item);
        }
        return $this->success_return('success', [
            'total' => $total,
            'list' => $data
        ]);
    }

    public function get($args = [])
    {
        $id = intval($args['id'] ?? 0);
        $data = $this->model->data_get(['id' => $id]);
        return $this->success_return('success', $data);
    }

    public function save_data($args): array
    {
        return $this->success_return('保存成功');
    }

    public function del_data($args): array
    {
        $id = intval($args['id'] ?? 0);
        $res = $this->model->data_del(['id' => $id]);
        return $this->success_return('success');
    }
}
